<template>
  <view>
    <!-- 导航栏 -->
    <view class="navigation_index" v-show="scrollTop > 350">
      <view class="n_context">
        <text class="iconfont  search_btn" @tap="toSearchPage" data-value="">&#xe638; </text>
        <text class="appName">下厨房 </text>
      </view>
    </view>

    <!-- 菜篮子模块 -->
    <view class="addFoodList">
      <text class="iconfont">&#xe608;</text>
    </view>

    <!-- 轮播图 -->
    <view class="container">
      <swiper class='test-h custom-swiper' :current="current" :duration="500" :interval="5000" :circular="true"
        :autoplay="false" :onChange="handleSwiperChange">
        <block v-for="(item, index) in imgUrls" :key="index">
          <swiper-item @tap="toInfoPage" :data-type="item.type">
            <image :src="item.url" class="slide-image" mode="aspectFill" />
            <view class="slide-description">
              <text>{{ item.title }}</text>
              <text>{{ item.description }}</text>
            </view>
          </swiper-item>
        </block>
      </swiper>
      <view class="custom-pagination">
        <block v-for="(     item, index     ) in       imgUrls      " :key="index">
          <view class="pagination-bullet" :class="{ active: current === index }" :data-index="index"
            @tap="onPaginationTap">
          </view>
        </block>
      </view>
    </view>
    <!-- 搜索 -->
    <view class="selectBox" @tap="toSearchPage" data-value="">
      <text class="iconfont">&#xe638;今天想吃点什么？</text>
    </view>
    <!-- 直播 -->
    <view class="living" @tap="showModal">

      <text class="type iconfont">
        {{ live_data.type }}
      </text>
      <view class="li-context">
        <text class="title">{{ live_data.title }}</text>
        <text class="time">{{ tomorrowDate_living }}</text>
      </view>
      <text class="booking">{{ live_data.booking }}</text>
    </view>
    <!-- 浮动弹窗  v-model:isOpened="isModalOpened"-->
    <AtFloatLayout v-model:isOpened="isOpened" :onClose="handleClose">
      <view class="living_booking">
        <view class="iconfont live_down">&#xf02a9;</view>
        <view class="live_font">厨</view>
        <view class="iconfont live_title">一起下厨房</view>
        <view class="live_video iconfont">视频号</view>
        <view class="live_time">明天12:00开始直播</view>
        <view class="live_content">国宴贾大厨教您学做菜啦！</view>
        <view class="booking_btn" :class="{ is_booking: is_booking }" @tap="booking">{{ booking_text }}</view>
      </view>
    </AtFloatLayout>


    <!-- hots模块 -->
    <view class="hots">
      <block v-for="(   item, index   ) in          hot_list         " :key="index">
        <view class="hotItem" @tap="getHrefWay($event)" :data-index='index' :data-value='item.title'>
          <image :src=item.imgSrc mode="aspectFill" />
          <text>{{ item.title }}</text>
        </view>
      </block>
    </view>

    <!-- menus模块 -->
    <view class="menus">
      <block v-for="(         item, index         ) in          menus_list         " :key="index">
        <view class="menuItem" @tap="toMenuInfoPage(item)">
          <image :src="item.imgSrc" mode="aspectFill" />
          <text>{{ item.title }}</text>
        </view>
      </block>
      <view class="data_none" v-if="pageInfo.isEnd">到底啦~~</view>
      <view class="limit-mask" v-if="!isLogin">
        <view class="limit-mask-wall"></view>
        <view class="limit-mask-tip" @tap="toLoginPage">登录查看更多菜谱</view>
      </view>
    </view>

    <!-- 提示用户登录 -->
    <LoginTip ref="loginTip" v-if="!isLogin"></LoginTip>
  </view>
</template>


<script setup>
  import { ref, onMounted, reactive, inject } from 'vue';
  import './index.scss';
  import LoginTip from '../../components/LoginTip.vue';
  import Taro, { useDidShow, usePageScroll, useReachBottom } from "@tarojs/taro";
  import { AtFloatLayout } from 'taro-ui-vue3';

  // 注入配置
  const config = inject('config');
  const baseUrl = config.baseUrl; // 从全局配置中读取 baseUrl


  // 显示页面时回到顶端函数
  const scrollToTop = () => {

    Taro.pageScrollTo({
      scrollTop: 400,
      // 可选，滚动动画的时长
      duration: 300
    });
  };


  //顶部搜索显示 获取下滑的距离
  const scrollTop = ref(0);
  usePageScroll((res) => {
    scrollTop.value = res.scrollTop;
  });

  /*
  
    轮播图模块 
  
  */

  // 切换轮播图
  const current = ref(0);
  const handleSwiperChange = (e) => {
    current.value = e.detail.current;
  };

  const onPaginationTap = (event) => {
    const index = event.target.dataset.index;
    if (index !== undefined) {
      current.value = parseInt(index, 10);
    }
  };
  // 轮播图图片信息
  const imgUrls = [
    {
      type: 'niuleitiao',
      url: 'https://imgs.699pic.com/images/502/477/430.jpg!list1x.v2',
      title: '优质澳洲谷饲牛肋条',
      description: '这个部位做什么都好吃'
    },
    {
      type: 'niupai',
      url: 'https://imgs.699pic.com/images/500/826/444.jpg!list1x.v2',
      title: '性价比超高牛排边角料',
      description: '1/3价格get餐厅同款'
    },
    {
      type: 'mianbao',
      url: 'https://imgs.699pic.com/images/350/075/242.jpg!list2x.v1',
      title: '手作碱水面包',
      description: '比馒头抗饿  比煎饼更香'
    },
  ];

  // 轮播图跳转文章页面
  const toInfoPage = (e) => {
    Taro.navigateTo({
      url: `../detail/articles/${e.currentTarget.dataset.type}/${e.currentTarget.dataset.type}`,
    })

  }


  /* 
  
    直播模块
  
  */

  // 直播信息
  const tomorrowDate_living = ref('');
  // 获取明天日期函数
  const calculateTomorrow = () => {
    // 获取当前日期
    const today = new Date();

    // 计算明天的日期
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    // 格式化日期为 YYYY-MM-DD
    const year = tomorrow.getFullYear();
    const month = (tomorrow.getMonth() + 1).toString().padStart(2, '0');
    const date = tomorrow.getDate().toString().padStart(2, '0');
    const tomorrowDay = `${month}-${date}`;

    // 获取星期几
    const weekdays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const dayOfWeek = weekdays[tomorrow.getDay()];
    tomorrowDate_living.value = `${tomorrowDay}（${dayOfWeek}）12:00直播`;
  };
  const live_data = ref({
    type: "直播",
    title: "国宴大厨教您学做菜啦",
    booking: "预约",
  });
  // 浮空弹窗
  const isOpened = ref(false);
  // 打开弹窗的方法
  const showModal = () => {
    Taro.showLoading({
      title: '请稍候...',
    })
    setTimeout(function () {
      Taro.hideLoading()
      isOpened.value = true;
    }, 300)

  };
  // 预约直播
  const booking_text = ref('预约直播');
  const is_booking = ref(false);
  const booking = (e) => {
    Taro.showLoading({
      title: '请稍候...',
    })
    setTimeout(function () {
      Taro.hideLoading()
      isOpened.value = true;
    }, 300)
    is_booking.value = !is_booking.value;
    booking_text.value = is_booking.value ? "已预约直播" : "预约直播"
    live_data.value.booking = is_booking.value ? "已预约" : "预约"
  }
  // 关闭执行的函数
  const handleClose = () => {
    isOpened.value = false;
  };


  /* 
  
    hot模块
    
  */
  // hot图片
  const url_header = 'https://images.weserv.nl/?url=https://gitee.com/xi0503/cooking-applet/raw/master/src/userData/img/index_hots/';
  const hot_list = [
    {
      imgSrc: `${url_header}jcc.png`,
      title: '家常菜'
    },
    {
      imgSrc: `${url_header}ksc1.png`,
      title: '快手菜'
    },
    {
      imgSrc: `${url_header}xfc.png`,
      title: '下饭菜'
    },
    {
      imgSrc: `${url_header}zc.png`,
      title: '早餐'
    },
    {
      imgSrc: `${url_header}hp.png`,
      title: '烘培'
    },
    {
      imgSrc: `${url_header}gd.png`,
      title: '更多'
    },
  ];

  const getHrefWay = (e) => {
    const hot_index = e.currentTarget.dataset.index;
    if (hot_index != hot_list.length - 1) toSearchPage(e);
    else toMorePage(e)
  }


  /* 
      
      菜单列表模块
      
  */
  const menus_list = ref([]);
  const pageInfo = ref({
    page: 2,
    isLoading: false,
    isEnd: false,
  })



  /*
  
      页面跳转模块
  
  */

  // 跳转菜谱详细页面
  const toMenuInfoPage = (item) => {
    if (getIsLogin()) return;
    Taro.navigateTo({
      url: `../detail/menuInfo/menuInfo?recipeId=${item.recipeId}&userId=${curUserId.value}`
    });
  }

  // 点击跳转搜索页面
  const toSearchPage = (e) => {
    const searchValue = e.currentTarget.dataset.value;
    Taro.navigateTo({
      url: `../detail/search/search?searchValue=${searchValue}`,
    })
  };

  /* 跳转更多页面 */
  const toMorePage = (e) => {
    Taro.navigateTo({
      url: `../detail/dishClassify/dishClassify`,
    })
  };

  //跳转到登录界面
  const toLoginPage = () => {
    Taro.navigateTo({
      url: `../detail/login/login`,
    })
  }


  //获取菜谱信息
  const getMenuInfo = () => {

    Taro.request({
      url: `${baseUrl}/recipe/getAllRecipes?page=${1}`,
      success: function (res) {
        menus_list.value = res.data.data
      }
    })
  }



  // 登录弹窗
  const loginTip = ref(null);

  // 存放当前登录用户
  const curUserId = ref();

  // 判断用户是否登录
  const isLogin = ref(false);
  function getIsLogin() {
    if (loginTip.value != null) loginTip.value.toLoginPage = toLoginPage;
    // 通过查看本地是否存放用户id判断用户是否登录
    isLogin.value = !(curUserId.value === "");
    if (!isLogin.value) {
      if (loginTip.value !== null)
        loginTip.value.isHidden = false;
      return true
    } else return false;
  }

  // 上拉触底时的回调 获取更多菜谱数据
  Taro.useReachBottom(() => {
    if (pageInfo.value.isLoading | !isLogin.value) {
      pageInfo.value.isEnd = true;
      return
    };
    pageInfo.value.isLoading = true;
    showLoading("加载中");
    Taro.request({
      url: `${baseUrl}/recipe/getAllRecipes?page=${pageInfo.value.page}`,
      success: function (res) {
        if (res.data.data.length === 0) {
          pageInfo.value.isEnd = true;
        }
        else {
          pageInfo.value.page += 1;
          menus_list.value = menus_list.value.concat(res.data.data);
          pageInfo.value.isLoading = false;
        }
        setTimeout(() => {
          hideLoading();
        }, 100);
      }
    })
  })

  // 显示加载中提示
  function showLoading(title) {
    Taro.showLoading({
      title: `${title}`,
      mask: true,
    })
  };
  // 隐藏加载中提示
  function hideLoading() {
    Taro.hideLoading();
  };




  //加载完组件执行
  onMounted(() => {
    console.log(11);
    getMenuInfo();
    scrollToTop();
    calculateTomorrow();
    showLoading()
  });

  Taro.useDidShow(() => {

    curUserId.value = Taro.getStorageSync('userId')
    getIsLogin();
    hideLoading();


  })



</script>